package com.urea.system.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.util.WxMaConfigHolder;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.urea.common.core.domain.AjaxResult;
import com.urea.common.core.domain.entity.Customer;
import com.urea.common.core.domain.model.LoginUser;
import com.urea.system.domain.vo.CustomerVo;
import com.urea.system.service.ICustomerService;
import com.urea.system.service.IWxMaUserService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.token.TokenService;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * 类描述:
 *
 * @author fangXu
 * @version 1.0
 * @date 2023/8/10 14:49
 */
//@Service
@Slf4j
public class WxMaUserServiceImpl implements IWxMaUserService {
//    @Autowired
    private  WxMaService wxMaService;
    @Autowired
    private ICustomerService customerService;


    /**
     * 小程序登录
     *
     * @param vo 用户信息
     * @return 结果
     */
    @Override
    public AjaxResult login(CustomerVo vo) {
        if (StringUtils.isBlank(vo.getCode())) {
            return AjaxResult.error("code不可为空");
        }
        if (!wxMaService.switchover(vo.getAppId())) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", vo.getAppId()));
        }

        try {
            WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(vo.getCode());
            log.info("##########小程序登录结果:{}################",session.toString());
            // todo 根据返回值 判断 报错
            // 获取用户openId
            String openid = session.getOpenid();
            if (StringUtils.isBlank(openid)){
                return AjaxResult.error("openid为空,请稍候重试");
            }
            LoginUser loginUser = new LoginUser();
            // 根据openId获取用户信息
            Customer customer = customerService.getOne(Wrappers.lambdaQuery(Customer.class).eq(Customer::getOpenId, openid));
            loginUser.setCustomerUser(customer);
            if (Objects.isNull(customer)){
                // 用户为空,创建用户信息
                Customer user = new Customer();
                BeanUtils.copyProperties(vo,user);
                customerService.save(user);
                loginUser.setCustomerUser(user);
                loginUser.setUserId(user.getId());
            }
            // 获取token 返回前端
//            tokenService.allocateToken()
            return AjaxResult.success(session);
        } catch (WxErrorException e) {
            log.error(e.getMessage(), e);
            return AjaxResult.error(e.toString());
        } finally {
            WxMaConfigHolder.remove();//清理ThreadLocal
        }
    }
}
